import React from 'react';
import ReactDOM from 'react-dom';
import { connect } from 'react-redux';
import { Toast } from 'antd-mobile';
import Swiper from '../../../assets/js/libs/swiper.min.js';
import * as utils from '../../../assets/js/utils/index';
import action from '../../../store/actions/index';
import config from '../../../assets/js/conf/config';
import TweenMax from '../../../assets/js/libs/TweenMax.min.js';
import * as Request from '../../../services/home/details';
import '../../../assets/css/common/swiper.min.css';
import Css from '../../../assets/css/goods/details_item.css';

class GoodsDetailsItem extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            bMask: false,
            sCartPanel: false,
            gid: !!props.location.search ? utils.localParam(this.props.location.search).search.gid : '',
            attr: [],
            iAmount: 1,
            aSlide: [],
            aReviews: [],
            aGoodsInfo: { title: '', price: '', freight: '', sales: '', gid: '' },
            iReviewsTotal: 0
        }
        this.bMove = false;
    }

    componentDidMount(){
        const { search: { gid } } = utils.localParam(this.props.location.search);
        utils.setScrollTop();
        this.initSwiper(gid);
        this.getGoodsAttr(gid);
        this.getReviews(gid);
    }  

    componentWillUnmount(){
        //页面卸载时，重写setState,避免内存溢出
        this.setState = (state, callback) => {
            return ;
        }
    }

    //获取轮播图数据以及商品信息
    initSwiper(gid){
        Request.getSwiper(gid).then(res => {
            if(res.code === 200){
                const { bodys, images, ...goodsInfo } = res.data;
                this.setState({ aSlide: images, aGoodsInfo: goodsInfo }, () => {
                    new Swiper(this.refs['swiper-wrap'], {
                        pagination: { el: this.refs['swiper-pagination'] }
                    });
                });
            }
        });
    }

    //获取商品规格属性
    getGoodsAttr(gid){
        Request.getGoodsAttr(gid).then(res => {
            res.code === 200 && this.setState({ attr: res.data });
        });
    }

    //获取商品评价
    getReviews(gid){
        Request.getReviews(gid).then(res => {
            if(res.code === 200){
                this.setState({ aReviews: res.data, iReviewsTotal: res.pageinfo.total }, () => {
                    utils.lazyImg(); //图片懒加载
                });
            }
        });
    }

    //显示购物车面板
    showCartPanel(){
        this.setState({ bMask: true, sCartPanel: true }, () => {
            this.refs['mask'].addEventListener('touchmove', function(e){ e.preventDefault(); }, false);
        });
    }

    //隐藏购物车面板
    hideCartPanel(){
        !this.bMove && this.setState({ bMask: false, sCartPanel: false });
    }

    //加入收藏
    addFav(){
        Toast.info('收藏成功！', 2);
    } 

    //路由切换
    goPage(url){
        this.props.history.replace(config.path+url);
    }

    //选择商品属性
    selectAttrVal(index, kndex){
        const aTempAttr = utils.deepClone(this.state.attr);
        aTempAttr[index].values.map((ptem, pndex) => {
            if(pndex !== kndex){ ptem.checked = false; }
        });
        aTempAttr[index].values[kndex].checked = !aTempAttr[index].values[kndex].checked;
        this.setState({ attr: aTempAttr });
    }

    //减少购买数量
    decAmount(){
        let aTempAMount = Number(utils.deepClone(this.state.iAmount));
        if(aTempAMount > 1){
            this.setState({ iAmount: --aTempAMount });
        }
    }

    //增加购买数量
    incAmount(){
        let aTempAMount = Number(utils.deepClone(this.state.iAmount));
        this.setState({ iAmount: ++aTempAMount });
    }

    //加入购物车抛物线动画
    addCart(){
        const that = this;
        this.checkAttrVal(() => {
            if(!this.bMove){
                this.bMove = true;
                const oGoodsInfo = this.refs['goods-info'], oGoodsImg = this.refs['goods-img'];
                const cartIcon = ReactDOM.findDOMNode(document.getElementById('cardIcon'));
                const oCloneImg = oGoodsImg.cloneNode(true); //true表示内部所有的子节点一起clone
                oCloneImg.style.cssText = 'position:absolute;left:0.2rem;top:0.47rem;width:0.4rem;height:0.4rem;z-index:1;'
                oGoodsInfo.appendChild(oCloneImg);
                const cartPanelTop = this.refs['cartPanel'].offsetTop;
                let srcImgX = oGoodsImg.offsetLeft, srcImgY = oGoodsImg.offsetTop;
                let cartIconLeft = cartIcon.offsetLeft, cartIconTop = cartIcon.offsetTop;
                TweenMax.to(oCloneImg, 0.2, { rotation: 360, repeat: -1 });
                TweenMax.to(oCloneImg, 2, {bezier:[{x: srcImgX, y: -100}, {x: srcImgX+30, y: -130}, {x: (cartIconLeft-srcImgX), y: (cartIconTop-srcImgY-cartPanelTop)}], onComplete: function(){
                    oCloneImg.remove();
                    that.bMove = false;
                }});
                const { sales, ...goodsInfo } = this.state.aGoodsInfo;
                const { attr, iAmount, aSlide } = this.state;
                const attrs = [];
                attr.map((item, index) => {
                    const itemAttr = { attrid: item.attrid, title: item.title };
                    if(item.values && item.values.length > 0){
                        const params = [];
                        item.values.map(ktem => {
                            ktem.checked && params.push({ paramid: ktem.vid, title: ktem.value });
                        });
                        itemAttr['param'] = params;
                    }
                    attrs.push(itemAttr);
                });
                this.props.dispatch(action.cart.getCartSource({...goodsInfo, amount: iAmount, img: aSlide[0], checked: true, attrs}));
            }
        });
    }

    //监测是否选择属性值
    checkAttrVal(callback){
        const { attr } = this.state;
        let bSelect = false, attrName = '';
        if(attr.length > 0){
            for(let key in attr){
                bSelect = false;
                for(let key2 in attr[key].values){  
                    if(attr[key].values[key2].checked){
                        bSelect = true;
                        break;
                    }
                }
                if(!bSelect){
                    attrName = attr[key].title;
                    break;
                }
            }
            bSelect ? callback() : Toast.info(`请选择${attrName}`, 2);
        }
    }

    //改变数量
    changeAmount(e){
        let amount = 1;
        if(e.target.value !== ''){
            amount = e.target.value.replace(/[a-zA-Z]|[\u4e00-\u9fa5]|[#|*|,|+|;|\.]/g, '');
            if(amount === ''){ amount = 1 }
        }
        this.setState({ iAmount: amount });
    }

    render(){
        const { bMask, sCartPanel, gid, attr, iAmount, aSlide, aGoodsInfo, aReviews, iReviewsTotal } = this.state;
        return (
            <div>
                {/* 轮播图 */}
                <div ref='swiper-wrap' className={Css['swiper-wrap']}>
                    <div className='swiper-wrapper'>
                        {
                            aSlide.length > 0 ? aSlide.map((item, index) => {
                                return (
                                    <div key={index} className='swiper-slide'><img src={item} alt='' /></div>
                                )
                            }) : ''
                        }
                    </div>
                    <div ref='swiper-pagination' className="swiper-pagination"></div>
                </div>
                {/* 商品信息 */}
                <div className={Css['goods-ele-main']}>
                    <div className={Css['goods-title']}>{aGoodsInfo.title}</div>
                    <div className={Css['price']}>￥{aGoodsInfo.price}</div>
                    <div className={Css['sales-wrap']}>
                        <div>快递：{aGoodsInfo.freight}元</div>
                        <div>月销量{aGoodsInfo.sales}件</div>
                    </div>
                </div>
                {/* 商品评价 */}
                <div className={Css['reviews-main']}>
                    <div className={Css['reviews-title']}>商品评价（{iReviewsTotal}）</div>
                    <div className={Css['reviews-wrap']}>
                        {
                            aReviews.length > 0 ? aReviews.map((item, index) => {
                                return (
                                    <div key={index} className={Css['reviews-list']}>
                                        <div className={Css['userinfo']}>
                                            <div className={Css['head']}><img src={require('../../../assets/images/common/lazyImg.jpg')} data-echo={item.head} alt='' /></div>
                                            <div className={Css['nickname']}>{item.nickname}</div>
                                        </div>
                                        <div className={Css['reviews-content']}>{item.content}</div>
                                        <div className={Css['reviews-date']}>{item.times}</div>
                                    </div>
                                )
                            }) : <div className='null-item'>暂无评价</div>
                        }
                    </div>
                    <div className={iReviewsTotal > 0 ? Css['reviews-more'] : Css['reviews-more']+' hide'} onClick={() => this.goPage('goods/details/reviews?gid='+gid)}>查看更多评价</div>
                </div>
                {/* 底部按钮 */}
                <div className={Css['bottom-btn-group']}>
                    <div className={Css['btn']+' '+Css['fav']} onClick={() => this.addFav()}>收藏</div>
                    <div className={Css['btn']+' '+Css['cart']} onClick={() => this.showCartPanel()}>加入购物车</div>
                </div>
                {/* 购物车面板 */}
                <div className={bMask ? Css['mask'] : Css['mask']+' hide'} ref='mask'></div>
                <div ref='cartPanel' className={sCartPanel ? Css['card-panel']+' '+Css['up'] : Css['card-panel']+' '+Css['down']}>
                    <div ref='goods-info' className={Css['goods-info']}>
                        <div className={Css['close-panel-wrap']}>
                            <div className={Css['spot']}></div>
                            <div className={Css['line']}></div>
                            <div className={Css['close']} onClick={() => this.hideCartPanel()}></div>
                        </div>
                        <div ref='goods-img' className={Css['goods-img']}>
                            <img src={aSlide.length > 0 ? aSlide[0] : ''} alt='' />
                        </div>
                        <div className={Css['goods-wrap']}>
                    <div className={Css['goods-title']}>{aGoodsInfo.title}</div>
                            <div className={Css['price']}>￥{aGoodsInfo.price}</div>
                            <div className={Css['goods-code']}>商品编码：{aGoodsInfo.gid}</div>
                        </div>
                    </div>
                    <div className={Css['attr-wrap']}>
                        {
                            attr.length > 0 ? attr.map((item, index) => {
                                return (
                                    <div key={item.attrid} className={Css['attr-list']}>
                                        <div className={Css['attr-name']}>{item.title}</div>
                                        <div className={Css['val-wrap']}>
                                            {
                                                item.values.length > 0 ? item.values.map((ktem, kndex) => {
                                                    return (
                                                        <div key={ktem.vid} className={ktem.checked ? Css['val']+' '+Css['active'] : Css['val']} onClick={() => this.selectAttrVal(index, kndex)}>{ktem.value}</div>
                                                    )
                                                }) : ''
                                            }
                                        </div>
                                    </div>
                                )
                            }) : ''
                        }
                    </div>
                    <div className={Css['amount-wrap']}>
                        <div className={Css['amount-name']}>购买数量</div>
                        <div className={Css['amount-input-wrap']}>
                            <div className={iAmount <= 1 ? Css['btn']+' '+Css['dec']+' '+Css['active'] : Css['btn']+' '+Css['dec']} onClick={() => this.decAmount()}>-</div>
                            <div className={Css['amount-input']}><input type='tel' value={iAmount} onChange={(e) => this.changeAmount(e)} /></div>
                            <div className={Css['btn']+' '+Css['inc']} onClick={() => this.incAmount()}>+</div>
                        </div>
                    </div>
                    <div className={Css['sure-btn']} onClick={() => this.addCart()}>确认</div>
                </div>
            </div>
        )
    }
}

export default connect((store) => {
    return store;
})(GoodsDetailsItem);